package initalize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"project07_resume_web/src/global"
	"project07_resume_web/src/proto/resume_proto"
)

// 采用轮询的方式实现负载均衡，实现对user_srv服务的发现
func InitConn() {
	conn, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s",
		global.SrvConfig.ConsulConfig.Host,
		global.SrvConfig.ConsulConfig.Port,
		global.SrvConfig.ResumeConfig.Name), grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robbin"}`))
	if err != nil {
		panic(err)
	}

	client := resume_proto.NewResumeServerClient(conn)
	global.ResumeClient = client

}

func InitFileManager() {
	conn, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s",
		global.SrvConfig.ConsulConfig.Host,
		global.SrvConfig.ConsulConfig.Port,
		global.SrvConfig.Name), grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robbin"}`))
	if err != nil {
		panic(err)
	}
	client := resume_proto.NewResumeServerClient(conn)
	global.ResumeClient = client
}

//func InitConn2() {
//	consulInfo := global.SrvConfig.ConsulInfo
//	cfg := api.DefaultConfig()
//	cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)
//	client, err := api.NewClient(cfg)
//	if err != nil {
//		panic(err)
//	}
//	data, err := client.Agent().ServicesWithFilter(fmt.Sprintf(`Service=="%s"`, global.SrvConfig.UserSrv.Name))
//	if err != nil {
//		panic(err)
//	}
//	srvHost := ""
//	srvPort := 0
//	for _, value := range data {
//		srvHost = value.Address
//		srvPort = value.Port
//		break
//	}
//	if srvHost == "" {
//		panic(err)
//	}
//
//	conn, err := grpc.Dial(fmt.Sprintf("%s:%d", srvHost, srvPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
//	if err != nil {
//		panic(err)
//	}
//	global.UserClient = proto.NewUserServiceClient(conn)
//}
